import { AsrData } from "../classes/AsrData";
import { readUriToTextAndExplode } from "../readFileToText/openTextFile";
import { AsrDrawType, IAsrDrawItem } from "../interfaces/IAsrDrawItem";
import { Coordinate } from "../coordParser/Coordinate";
import { RenderData } from "../classes/RadarRenderData";
import { RadarScreen } from "../RadarCanvasDrawer";
enum AsrDrawTypeOrder {
    REGION,
    GEO,
    AIRSPACE,
    FREETEXT,
    POSITION,
    SIDSTAR,
    ARTCCLB,
    AIRPORT,
    FIX,
    HAW,
    RUNWAY,
    VORNDB,
}
function getDrawOrderByItem(type: AsrDrawType) {
    switch (type) {
        case 'ARTCC low boundary':
            return AsrDrawTypeOrder.ARTCCLB;
        case 'Airports':
            return AsrDrawTypeOrder.AIRPORT;
        case 'Fixes':
            return AsrDrawTypeOrder.FIX;
        case 'Free Text':
            return AsrDrawTypeOrder.FREETEXT;
        case 'Geo':
            return AsrDrawTypeOrder.GEO;
        case 'High airways':
            return AsrDrawTypeOrder.HAW;
        case 'NDBs':
        case 'VORs':
            return AsrDrawTypeOrder.VORNDB;
        case 'Regions':
            return AsrDrawTypeOrder.REGION;
        case 'Runways':
            return AsrDrawTypeOrder.RUNWAY;
        case 'Sids':
        case 'Stars':
            return AsrDrawTypeOrder.SIDSTAR;

    }
}
/**
 * 重新排序AsrData中的items
 * @param data 要重新排序的AsrData
 */
function reorderAsrItems(data: IAsrDrawItem[]) {
    return data.sort((a, b) => {
        return getDrawOrderByItem(a.type) - getDrawOrderByItem(b.type);
    });
}

export async function loadAsrFile(uri: string) {
    const result: AsrData = new AsrData();
    const lines = await readUriToTextAndExplode(uri, ';');
    for (const line of lines) {
        const items = line.split(':');
        switch (items.length) {
            case 2:
                result.settings.push({
                    flag: items[0],
                    data: items[1]
                });
                break;
            case 3:
                result.items.push({
                    type: items[0] as AsrDrawType,
                    name: items[1],
                    drawItem: items[2],
                    draw: true
                });
                break;
            case 5:
                result.windowArea = {
                    coord1: Coordinate.fromStr(items[1], items[2]),
                    coord2: Coordinate.fromStr(items[3], items[4])
                }
        }
    };
    result.items = reorderAsrItems(result.items);
    console.log('loadAsrFile', result);
    const rotation = result.settings.find(i => i.flag === 'DisplayRotation');
    if (rotation !== undefined) {
        RadarScreen.setRotation(Number(rotation.data));
    }
    RenderData.asr.set(uri, result);
}